/**
 * @User: vitobo
 * @Date: 2024-05-28
 * @Description: 字符串常量池
 *
 *  class文件常量池
 *  运行时常量池
 *  字符串常量池: 底层是一个StringTable的哈希表,实际上是一个固定大小的HashTable
 *     在常量池中, 只会存储一份常量值
 *
 *
 *
 */
public class Test2 {

    // StringBuilder 和 StringBuffer
    public static void main(String[] args) {
        StringBuilder sb1 = new StringBuilder("hello");
        StringBuilder sb2 = sb1;

        sb1.append(' ');
        sb1.append("world");
        sb1.append(123);
        System.out.println(sb1);
        System.out.println(sb1==sb2);
        System.out.println(sb1.charAt(0));
        System.out.println(sb1.length());
        System.out.println(sb1.capacity());

        sb1.setCharAt(0, 'H');
        sb1.insert(0, "beautiful");
        System.out.println(sb1);

        System.out.println(sb1.indexOf("hello"));
        System.out.println(sb1.lastIndexOf("hello"));

        sb1.deleteCharAt(1);
        sb1.delete(5,8);
        System.out.println(sb1);



    }

    // 字符串修改
    public static void main3(String[] args) {
        long start = System.currentTimeMillis();
        String s = "";
        for(int i = 0; i < 10000; ++i){
            s += i;
        }
        long end = System.currentTimeMillis();
        System.out.println(end - start);

        start = System.currentTimeMillis();
        StringBuffer sbf = new StringBuffer("");
        for(int i = 0; i < 10000; ++i){
            sbf.append(i);
        }
        end = System.currentTimeMillis();
        System.out.println(end - start);


        start = System.currentTimeMillis();
        StringBuilder sbd = new StringBuilder();
        for(int i = 0; i < 10000; ++i){
            sbd.append(i);
        }
        end = System.currentTimeMillis();
        System.out.println(end - start);
    }

    //intern方法:手动将创建的String对象添加到常量池中
    public static void main2(String[] args) {
        char[] ch = new char[]{'a','b','c'};
        String s1 = new String(ch);

        s1.intern();
        String s2 = "abc";
        System.out.println(s1==s2);
    }


    public static void main1(String[] args) {
        String str1 = "abcd";
        String str2 = "abcd";
        String str3 = new String("abcd");
        String str4 = new String("abcd");

        System.out.println(str1 == str2);  // true
        System.out.println(str3 == str4);  // false
        System.out.println(str1 == str3);  // false

    }
}
